package base;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.digest.DigestUtils;

import redis.clients.jedis.Jedis;

public class BaseTool {
	/** ----------------------------------------------------------------------------------------------------------------------------- */
	/** 返回字符串 */
	public static String getStringByTime(int length) {
		String date = System.currentTimeMillis() + "";
		return date.substring(date.length() - length, date.length());
	}

	/** 返回字符串 */
	public static String getStringByChar(int length) {
		String str = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789";
		StringBuffer sb = new StringBuffer();
		Random random = new Random();

		for (int i = 0; i < length; i++) {
			int number = random.nextInt(62);
			sb.append(str.charAt(number));
		}

		return sb.toString();
	}

	/** 是否不为空 */
	public static boolean isNotEmpty(Object obj) {
		if (obj == "" || obj == "null" || obj.equals("") || obj.equals("null") || obj == null) {
			return false;
		}
		return true;
	}

	/** 是否不为空 */
	public static boolean isNotEmpty2(Object obj) {
		if (obj == "null" || obj.equals("") || obj.equals("null") || obj == null) {
			return false;
		}
		return true;
	}

	/** 是否为地址 */
	public static boolean isURL(String str) {
		Pattern pattern = Pattern.compile("^http(s)?://.*$");
		Matcher matcher = pattern.matcher(str);
		return matcher.matches();
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	/** 睡眠等待 */
	public static void sleepWait(int milliSecond) {
		try {
			Thread.sleep(milliSecond);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 返回当前日期 */
	public static String getCurrentDate(String dateFormat) {
		// 格式化日期：yyyy-MM-dd、HH:mm:ss:SS、yyyyMMddHHmmssSS
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Date date = new Date();
		return sdf.format(date);
	}

	/** 返回延迟日期 */
	public static String getDelayDate(String dateFormat, int addDay) {
		// 格式化日期：yyyy-MM-dd、HH:mm:ss:SS、yyyyMMddHHmmssSS
		SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_YEAR, +addDay);
		Date date = cal.getTime();
		return sdf.format(date);
	}

	/** 是否为日期 */
	public static boolean isDate(String str) {
		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			dateFormat.parse(str);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	/** 返回数据类型 */
	public static String getDataType(Object obj) {
		int length = obj.getClass().getName().lastIndexOf(".");
		return obj.getClass().getName().substring(length + 1);
	}

	/** 返回数据类型 */
	public static String getDataType2(Object obj) {
		String type = "";

		if (obj instanceof String) {
			type = "string";
		} else if (obj instanceof Integer) {
			type = "int";
		} else if (obj instanceof Float) {
			type = "float";
		} else if (obj instanceof Double) {
			type = "double";
		} else if (obj instanceof Long) {
			type = "long";
		} else if (obj instanceof Boolean) {
			type = "boolean";
		} else if (obj instanceof Date) {
			type = "date";
		}

		return type;
	}

	/** String转Int */
	public static int stringToInt(String str) {
		return Integer.parseInt(str);
	}

	/** String转Float */
	public static float stringToFloat(String str) {
		return Float.parseFloat(str);
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	/** 返回MD5加密 */
	public static String getMD5(String str) {
		return DigestUtils.md5Hex(str);
	}

	/** 返回URL编码 */
	public static String getURLEncoder(String str) {
		String encoderString = "";

		try {
			encoderString = URLEncoder.encode(str, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return encoderString;
	}

	/** 返回URL解码 */
	public static String getURLDecoder(String str) {
		String decodeString = "";

		try {
			decodeString = URLDecoder.decode(str, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return decodeString;
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	public static Connection conn = null;

	/** 连接SQL */
	public static void connectionSQL() {
		try {
			Class.forName(BaseData.DB_Driver);
			conn = DriverManager.getConnection(BaseData.DB_URL, BaseData.DB_User, BaseData.DB_Pass);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 执行SQL */
	public static void executeSQL(String executeSQL) {
		try {
			if (conn == null) {
				BaseTool.connectionSQL();
			}

			Statement stmt = conn.createStatement();
			stmt.executeUpdate(executeSQL);
			// System.out.println("执行成功：" + executeSQL);

			stmt.close();
			// conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/** 查询SQL，返回指定列的Object */
	public static Object querySQL(String querySQL, String queryTypt, String queryColumn) {
		Object queryResult = "";

		try {
			if (conn == null) {
				BaseTool.connectionSQL();
			}

			Statement stmt = conn.createStatement();
			ResultSet resu = stmt.executeQuery(querySQL);

			while (resu.next()) {
				// 在jenkins服务端执行强转有误，先转Integer，再转int
				if (queryTypt.equals("int")) {
					queryResult = resu.getInt(queryColumn);
				} else if (queryTypt.equals("long")) {
					queryResult = resu.getLong(queryColumn);
				} else if (queryTypt.equals("float")) {
					queryResult = resu.getFloat(queryColumn);
				} else if (queryTypt.equals("double")) {
					queryResult = resu.getDouble(queryColumn);
				} else if (queryTypt.equals("string")) {
					queryResult = resu.getString(queryColumn);
				}
				// System.out.println("查询成功：" + querySQL);
			}

			resu.close();
			stmt.close();
			// conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return queryResult;
	}

	/** 查询SQL，返回指定列的ArrayList */
	public static ArrayList<String> querySQL2(String querySQL, String queryTypt, String queryColumn) {
		ArrayList<String> queryResult = new ArrayList<String>();

		try {
			if (conn == null) {
				BaseTool.connectionSQL();
			}

			Statement stmt = conn.createStatement();
			ResultSet resu = stmt.executeQuery(querySQL);

			while (resu.next()) {
				if (queryTypt.equals("arrayList")) {
					queryResult.add(resu.getString(queryColumn));
				}
				// System.out.println("查询成功：" + querySQL);
			}

			resu.close();
			stmt.close();
			// conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return queryResult;
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	public static Jedis jedis = null;

	/** 连接Redis */
	public static Jedis connectRedis() {
		if (jedis == null) {
			jedis = new Jedis(BaseData.Redis_Host, BaseData.Redis_Port);
			jedis.auth(BaseData.Redis_Auth);
		}

		return jedis;
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	/** 字符串格式化 */
	public static String stringFormat(String str) {
		str = str.replace(" ", "");
		str = str.replace("\n", "");
		str = str.replace("\t", "");
		return str;
	}

	/** JSON格式化 */
	public static String jsonFormate(String jsonString) {
		StringBuffer sb = new StringBuffer();
		int length = jsonString.length();
		int number = 0;
		char key = 0;

		for (int i = 0; i < length; i++) {
			key = jsonString.charAt(i);

			if ((key == '[') || (key == '{')) {
				if ((i - 1 > 0) && (jsonString.charAt(i - 1) == ':')) {
					sb.append('\n');
					sb.append(jsonIndent(number));
				}
				sb.append(key);
				sb.append('\n');
				number++;
				sb.append(jsonIndent(number));
				continue;
			}
			if ((key == ']') || (key == '}')) {
				sb.append('\n');
				number--;
				sb.append(jsonIndent(number));
				sb.append(key);
				if (((i + 1) < length) && (jsonString.charAt(i + 1) != ',')) {
					sb.append('\n');
				}
				continue;
			}
			if ((key == ',')) {
				sb.append(key);
				sb.append('\n');
				sb.append(jsonIndent(number));
				continue;
			}
			sb.append(key);
		}

		return sb.toString();
	}

	/** JSON缩进 */
	public static String jsonIndent(int number) {
		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < number; i++) {
			sb.append("\t");
		}

		return sb.toString();
	}

	/** ----------------------------------------------------------------------------------------------------------------------------- */
	/** 日志信息(使用Notepad打开) */
	public static void logInfo(String executeTime, String testcase, String url, String responseStatusCode, String data, String responseString) {
		if (!url.contains("/login/userLogin")) {
			if (!BaseData.Log_Directory_Path.isDirectory()) {
				BaseData.Log_Directory_Path.mkdir();
			}

			try {
				BufferedWriter bw = new BufferedWriter(new FileWriter(BaseData.Log_File_Path, true));
				bw.append("-----------------------------------------------" + executeTime + "-----------------------------------------------").append("\n");
				bw.append("用例编号：" + testcase).append("\n");
				bw.append("请求地址：" + url).append("\n");
				bw.append("响应状态：" + responseStatusCode).append("\n");
				bw.append("请求数据：").append("\n").append(data).append("\n");
				bw.append("响应数据：").append("\n").append(responseString).append("\n");

				bw.newLine();
				bw.newLine();
				bw.flush();
				bw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}